<?php
class Payment extends CS_Controller
{
    public function _init()
    {
        $this->load->helper('common');
        $this->load->library('alipay/alipaypc', null, 'alipaypc');
        //$this->load->library('chinapay/chinapay', null, 'chinapay');
        $this->load->library('ccbpay/ccbpay', null, 'ccbpay');
        $this->load->model('pay_failure_log_model', 'pay_failure_log');
        $this->load->model('pay_method_model', 'pay_method');
        $this->load->model('tourism_goods_attr_model','tourism_goods_attr');
        $this->load->model('user_model', 'user');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('account_log_model', 'account_log');
        $this->load->model('tourism_order_main_model', 'tourism_order_main');
        $this->load->model('tourism_order_model', 'tourism_order');
        $this->load->model('tourism_order_product_model', 'tourism_order_product');
    }

    /**
     * 下完订单后的跳转方法
     * 去付款的界面
     */
    public function payOrderLine()
    {
        $last_order_sn = $this->session->userdata('last_order_sn');
        $result = $this->tourism_order_main->findByOrderMain($last_order_sn);
        $payResult = $this->tourism_order->getPayResultCount($last_order_sn);
        if ($result->num_rows() <= 0 || $payResult->num_rows() <= 0) {
            $this->alertJumpPre('订单信息不对。');
        }
        $totalPay = bcadd($payResult->row(0)->total_actual_price,$payResult->row(0)->total_transport_cost,2);
        if (bcsub($result->row(0)->order_amount,$totalPay,2) != 0) {
            $param['order_amount'] = $totalPay;
            $status = $this->tourism_order_main->updatePayOrderInfo($last_order_sn,$param);
            if(!$status){
                $this->alertJumpPre('网络出现问题，请刷新重试');
            }
        }
        $this->data['last_order_sn'] = $last_order_sn;
        $this->data['payResult'] = $payResult->row(0);
        $this->load->view('tourism/payment/payment', $this->data);
    }

    /**
     * 网银去支付方法。
     */
    public function orderToPay()
    {
        $order_sn = $this->input->post('order_sn');
        $pay_bank = (int)$this->input->post('pay_bank');
        // 获取要查看的订单
        // $order_sn = 15727104712556;
        $result = $this->tourism_order_main->findByOrderMain($order_sn);
        if ($result->num_rows() <= 0) {
            $this->alertJumpPre('订单信息不正确');
        }
        $orderInfo = $result->row();
        switch ($pay_bank) {
            case '99' :  //余额支付
                $userAccount = $this->user_account->findByUid($this->uid);
                $data['userAccount'] = $userAccount->row();
                $data['orderInfo'] = $orderInfo;
                $this->load->view('tourism/payment/balancePay', $data);
                break;
            case '201':    //微信支付
                $url = $this->config->wap_base_url."tourism_wx_call.php?order_id=".$order_sn;
                header("Location:$url");
                break;
            case '200' : //银联支付
                $BgRetUrl = site_url('tourism/paycallback/chinapayNotify');//异步
                $PageRetUrl = site_url('tourism/payment/chinapayReturn'); //同步
                $objPay = $this->chinapay->callChinapayApi($order_sn, $orderInfo->order_amount, 'notcart', $BgRetUrl, $PageRetUrl);
                break;
            case '1':      //支付宝支付
                $alipayParameter = $this->alipayParameter($pay_bank,$orderInfo);
                $this->alipaypc->callAlipayApi($alipayParameter);
                break;
            case '210' :    //建行支付
                $parameter = array(
                    'orderId' => $order_sn,
                    'payment' => $orderInfo->order_amount, //金额
                    'regInfo' => '', // 网站客户注册信息，中文需使用escape编码
                    'proInfo' => '', // 顾客购买的产品的信息，中文需使用escape编码
                    'remark1' => 'TOURISM' , //备注1 商品
                    'remark2' => ''
                );
                $this->ccbpay->callCcbPay($parameter);
                break;
            default :  //支付出现问题
                $this->redirect('tourism/tourism/payFail');
                break;
        }
    }
    
    /**
     * 获取支付宝需要参数。
     * @param paybank $bank_id
     * @param object $orderInfo
     * @param object $orderProductInfo
     * @return array
     */
    private function alipayParameter($pay_bank, $orderInfo)
    {
        $parameter = array(
            'out_trade_no' =>  $orderInfo->order_sn,
            'subject'      =>  $orderInfo->order_sn,
            'total_fee'    =>  $orderInfo->order_amount,
            'body'         =>  $orderInfo->order_sn,
            'notify_url'   =>  site_url('tourism/paycallback/alipayNotify'),
            'call_back_url'=>  site_url('tourism/payment/alipayReturn'),
            'show_url'     =>  site_url('tourism/tourism'),//展示body--url;
            'pay_method'   =>  $pay_bank,
        );
        $payBankCode = $this->pay_method->findByBankId($pay_bank);
        $parameter['defaultbank'] = $payBankCode->bank_code;
        return $parameter;
    }
    
    /**
     * 支付宝支付回调函数。
     */
    public function alipayReturn()
    {
        $response = $this->alipaypc->responseAlipayReturn();
        $order_sn = $this->input->get('out_trade_no');
        //验证是否支付
        $orderInfo = $this->whetherToPay($order_sn);

        //更新订单状态
        $getDate = $this->input->get();

        if ($response) { //$response付款成功；
            $params['order_state'] = 2;
            $params['order_status'] = 3;
            $params['pay_time'] = date('Y-m-d H:i:s');
            $params['pay_bank'] = 1;
            $this->tourism_order->updateByOrderMainSn($order_sn,$params);
            $param['status'] = 2;
            $this->tourism_order_main->updateStatus($order_sn,$param);
            //更新商品信息
            $tourismOrder = $this->tourism_order->findTourismGoods($order_sn);
            foreach ($tourismOrder->result() as $t=>$item) {
                $product_param['goods_attr_id'] = $item->goods_attr_id;
                $product_param['number'] = $item->number;
                $this->tourism_goods_attr->updateTourismSale($product_param);
            }
            //提醒供应商发货
            $tourismOrder = $this->tourism_order->findByOrderMainSn($order_sn);
            foreach ($tourismOrder->result() as $item) {
                if (!empty($item->pay_swim)) {  //更新U币
                    $this->user_account->updateUserAccountUb($this->uid,$item->pay_swim);
                }
                if (!empty($item->cellphone)) {
                    //$item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
                    $this->sendCommonSmsInfo($item->cellphone, 'SMS_136383536', ['providerName' => $item->user_name]);
                }
            }
            //更新商品信息结束
            $this->redirect('tourism/tourism/paySuccess');
        } else {
            $result = $this->pay_failure_log->findByOrderSn($order_sn);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($order_sn, $getDate, $response);
            }
            $this->redirect('tourism/tourism/payFail');
        }
    }
    
     /**
     * 银联同步支付
     */
    public function chinapayReturn()
    {
        $postData = $this->input->post();
        $response = $this->chinapay->responseChinapayApi($postData);
        $order_main_sn = (int)$this->input->post('orderno');
       
        $resultOrder = $this->tourism_order_main->findByOrderMain($order_main_sn);
        if( $resultOrder->num_rows()<=0 ){
           $this->redirect('tourism/tourism/payFail');
        }
        $orderInfo = $resultOrder->row();
        if ($response === true) { //$response付款成功；
            if( $orderInfo->status==2 ){
                 $this->redirect('tourism/tourism/paySuccess');
            }
            $this->db->trans_start();
            $params['order_state'] = 2;
            $params['order_status'] = 3;
            $params['pay_time'] = date('Y-m-d H:i:s');
            $params['pay_bank'] = 200;
            $this->tourism_order->updateByOrderMainSn($order_main_sn,$params);
            $param['status'] = 2;
            $this->tourism_order_main->updateStatus($order_main_sn,$param);
        
            //更新商品信息
            $tourismOrder = $this->tourism_order->findTourismGoods($order_main_sn);
            foreach ($tourismOrder->result() as $t=>$item) {
                $product_param['goods_attr_id'] = $item->goods_attr_id;
                $product_param['number'] = $item->number;
                $this->tourism_goods_attr->updateTourismSale($product_param);
            }
            $this->db->trans_complete();
            //提醒供应商发货
            $tourismOrder = $this->tourism_order->findByOrderMainSn($order_main_sn);
            foreach ($tourismOrder->result() as $item) {
                if( !empty($item->pay_swim) ){  //更新U币
                    $this->user_account->updateUserAccountUb($this->uid,$item->pay_swim);
                }
                if (!empty($item->cellphone)) {
                    //$item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
                    $this->sendCommonSmsInfo($item->cellphone, 'SMS_136383536', ['providerName' => $item->user_name]);
                }
            }
            $this->redirect('tourism/tourism/paySuccess');
        } else {
            $result = $this->pay_failure_log->findByOrderSn($order_main_sn);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($order_main_sn, $postData, array('status'=>$response));
            }
            $this->redirect('tourism/tourism/payFail');
        }
    }
    
    /**
     * 个人中心小订单支付
     */
    public function chinapayReturnU()
    {
        $postData = $this->input->post();
        $response = $this->chinapay->responseChinapayApi($postData);
        $order_sn = (int)$this->input->post('orderno');
        $result = $this->tourism_order->findByOrderSn($order_sn);
        if ($result->num_rows() <= 0) {
           $this->redirect('tourism/tourism/payFail');
        }
        $orderInfo = $result->row();
        if($orderInfo->order_state == 2 && $orderInfo->order_status == 3){
            $this->redirect('tourism/tourism/paySuccess');
        }
        if ($response === true) { // 支付成功
            /*开启事务*/
            $this->db->trans_start();
            $params['order_state'] = 2;
            $params['order_status'] = 3;
            $params['pay_time'] = date('Y-m-d H:i:s');
            $params['pay_bank'] = 1;
            $this->tourism_order->updateStatus($order_sn, $params);
            //更新商品信息
            $product = $this->tourism_order->findTourismGoods($order_sn, true);
            foreach ($product->result() as $item) {
                $product_param['goods_attr_id'] = $item->goods_attr_id;
                $product_param['number'] = $item->number;
                $this->tourism_goods_attr->updateTourismSale($product_param);
            }
            $this->db->trans_complete();
            //给供应商发短信，提醒供应商发货
            $tourismOrder = $this->tourism_order->findByOrderId($orderInfo->order_id);
            if( !empty($tourismOrder->pay_swim) ){  //更新U币
                $this->user_account->updateUserAccountUb($this->uid,$tourismOrder->pay_swim);
            }
            if (!empty($tourismOrder->cellphone)) {
                //$item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
                $this->sendCommonSmsInfo($tourismOrder->cellphone, 'SMS_136383536', ['providerName' => $tourismOrder->user_name]);
            }
            $this->redirect('tourism/tourism/paySuccess');
        } else {
            $result = $this->pay_failure_log->findByOrderSn($order_sn);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($order_sn, $postdata, $response);
            }
            $this->redirect('tourism/tourism/payFail');
        }
    }

    public function wxCompletePay($order_sn)
    {
        $err_msg = $this->input->get('err_msg');
        if ($err_msg && $err_msg == 'get_brand_wcpay_request:ok') {
            $resultOrder = $this->tourism_order_main->findByOrderMain($order_sn);
            $orderInfo = $resultOrder->row();
            if ($orderInfo->status == 2) {
                $this->redirect('tourism/tourism/paySuccess');
            } else {
                $this->redirect('tourism/tourism/payFail');
            }
            
            //更新商品信息结束
            $this->redirect('tourism/tourism/paySuccess');
        } else {
            $this->redirect('tourism/tourism/payFail');
        }
    }
    

    /**
     * 建行支付
     * 同步回调函数，主订单ORDERID
     */
    public function ccbpayReturn()
    {
        $response = $this->ccbpay->responseCcbReturn();
        $order_sn = $this->input->get('ORDERID', true);
        //验证是否支付
        $orderInfo = $this->whetherToPay($order_sn);

        //更新订单状态
        $getDate = $this->input->get();

        if ($response) { //$response付款成功；
            $params['order_state'] = 2;
            $params['order_status'] = 3;
            $params['pay_time'] = date('Y-m-d H:i:s');
            $params['pay_bank'] = 210;
            $this->tourism_order->updateByOrderMainSn($order_sn,$params);
            $param['status'] = 2;
            $this->tourism_order_main->updateStatus($order_sn,$param);
            //更新商品信息
            $tourismOrder = $this->tourism_order->findTourismGoods($order_sn);
            foreach ($tourismOrder->result() as $t=>$item) {
                $product_param['goods_attr_id'] = $item->goods_attr_id;
                $product_param['number'] = $item->number;
                $this->tourism_goods_attr->updateTourismSale($product_param);
            }
            //提醒供应商发货
            $tourismOrder = $this->tourism_order->findByOrderMainSn($order_sn);
            foreach ($tourismOrder->result() as $item) {
                
                if( !empty($item->pay_swim) ){  //更新U币
                    $this->user_account->updateUserAccountUb($this->uid,$item->pay_swim);
                }
                if (!empty($item->cellphone)) {
                    //$item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
                    $this->sendCommonSmsInfo($item->cellphone, 'SMS_136383536', ['providerName' => $item->user_name]);
                }
            }
            //更新商品信息结束
            $this->redirect('tourism/tourism/paySuccess');
        } else {
            $result = $this->pay_failure_log->findByOrderSn($order_sn);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($order_sn, $getDate, array('status'=>$this->ccbpay->getMessage()));
            }
            $this->redirect('tourism/tourism/payFail');
        }
    }

    /**
     * 建行支付
     * 个人中心小订单支付
     */
    public function ccbpayReturnU()
    {
        $response = $this->ccbpay->responseCcbReturn();
        $order_sn = $this->input->get('ORDERID', true);
        $result = $this->tourism_order->findByOrderSn($order_sn);
        if ($result->num_rows() <= 0) {
           $this->redirect('tourism/tourism/payFail');
        }
        $orderInfo = $result->row();
        if ($orderInfo->order_state == 2 && $orderInfo->order_status == 3) {
            $this->redirect('tourism/tourism/paySuccess');
        }
        if ($response == true) { // 支付成功
            /*开启事务*/
            $this->db->trans_start();
            $params['order_state'] = 2;
            $params['order_status'] = 3;
            $params['pay_time'] = date('Y-m-d H:i:s');
            $params['pay_bank'] = 210;
            $this->tourism_order->updateStatus($order_sn, $params);
            //更新商品信息
            $product = $this->tourism_order->findTourismGoods($order_sn, true);
            foreach ($product->result() as $item) {
                $product_param['goods_attr_id'] = $item->goods_attr_id;
                $product_param['number'] = $item->number;
                $this->tourism_goods_attr->updateTourismSale($product_param);
            }
            $this->db->trans_complete();
            //给供应商发短信，提醒供应商发货
            $tourismOrder = $this->tourism_order->findByOrderId($orderInfo->order_id);
            if( !empty($tourismOrder->pay_swim) ){  //更新U币
                $this->user_account->updateUserAccountUb($this->uid,$tourismOrder->pay_swim);
            }
            if (!empty($tourismOrder->cellphone)) {
                //$item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
                $this->sendCommonSmsInfo($tourismOrder->cellphone, 'SMS_136383536', ['providerName' => $tourismOrder->user_name]);
            }
            $this->redirect('tourism/tourism/paySuccess');
        } else {
            $result = $this->pay_failure_log->findByOrderSn($order_sn);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($order_sn, $this->input->get(), array('status'=>$this->ccbpay->getMessage()));
            }
            $this->redirect('tourism/tourism/payFail');
        }
    }

    /**
     * 余额支付过程
     */
    public function balancePayForm()
    {
        $uid      = $this->uid;
        $password = $this->input->post('password');
        $order_sn = $this->input->post('order_sn', true);
        $userInfo = $this->user->findOne(['uid' => $uid, 'payment_password' => md5($password)]);
        if ($userInfo->num_rows() <= 0) {
            return $this->ajaxJson(false, '支付密码填写有误~');
        }
        $userAccount = $this->user_account->findOne(['uid' => $uid]);
        if ($userAccount->num_rows() <= 0) {
            return $this->ajaxJson(false, '账户信息有误，请退出重新登录~');
        }
        $userAccount = $userAccount->row();

        //验证是否支付
        $resultOrder = $this->tourism_order_main->findByOrderMain($order_sn);
        if ($resultOrder->num_rows() <= 0) {
            return $this->ajaxJson(false, '订单信息不对。');
        }
        $orderInfo = $resultOrder->row();
        if ($orderInfo->status == 2) {
            //$this->redirect('tourism/tourism/paySuccess');
            return $this->ajaxJson(true, site_url('tourism/tourism/paySuccess'));
        }
        if ($orderInfo->status != 1) {
            return $this->ajaxJson(false, '订单状态有误');
        }

        //验证账户余额是否大于当前订单金额。
        if ($userAccount->amount_carry < $orderInfo->order_amount) {
            return $this->ajaxJson(false, '当前账户余额不足支付订单~');
        }

        $params['order_state']  = 2;
        $params['order_status'] = 3;
        $params['pay_time']     = date('Y-m-d H:i:s');
        $params['pay_bank']     = 99;

        $this->db->trans_begin();
        $status = $this->tourism_order->updateByOrderMainSn($order_sn, $params);
        $state = $this->tourism_order_main->updateStatus($order_sn, ['status' => 2]);

        //更新商品信息
        $tourismOrder = $this->tourism_order->findTourismGoods($order_sn);
        foreach ($tourismOrder->result() as $t => $item) {
            $product_param['goods_attr_id'] = $item->goods_attr_id;
            $product_param['number']        = $item->number;
            $this->tourism_goods_attr->updateTourismSale($product_param);
        }

        $product = $this->tourism_order->findByOrderMainSn($order_sn);
        $accountLog = [];
        foreach ($product->result() as $t=>$item) {
            $accountLog[$t]['order_id']     = $item->order_id;
            $accountLog[$t]['uid']          = $uid;
            $accountLog[$t]['amount']       = bcadd($item->order_pay_total, $item->transport_cost, 2);
            $accountLog[$t]['type']         = 1;//支付
            $accountLog[$t]['account_type'] = 1;//提现账户
            $accountLog[$t]['date']         = date('Y-m-d H:i:s',time());
            $accountLog[$t]['product_type'] = 'tourism';//提现账户
            if (!empty($item->pay_swim)) { //更新U币
                $this->user_account->updateUserAccountUb($uid, $item->pay_swim);
            }
        }
        //更新商品信息结束
        $updateAmountCarry = $this->user_account->updateAmountCarry($uid, $orderInfo->order_amount);
        $account_log = $this->account_log->insertBatch($accountLog);

        //提醒供应商发货
        $tourismOrder = $this->tourism_order->findByOrderMainSn($order_sn);
        foreach ($tourismOrder->result() as $item) {
            if (!empty($item->cellphone)) {
                //$item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
                $this->sendCommonSmsInfo($item->cellphone, 'SMS_136383536', ['providerName' => $item->user_name]);
            }
        }
        if ($this->db->trans_status() === true && $status && $state && $updateAmountCarry && $account_log) {
            $this->db->trans_complete();
            return $this->ajaxJson(true, site_url('tourism/tourism/paySuccess'));
        } else {
            $this->db->trans_rollback();
            return $this->ajaxJson(false, '网络延迟错误~');
            //$this->redirect('tourism/tourism/payFail');
        }
    }

    public function whetherToPay($orderSn)
    {
        $resultOrder = $this->tourism_order_main->findByOrderMain($orderSn);
        if ($resultOrder->num_rows() <= 0) {
            $this->alertJumpPre('订单信息不对。');
        }
        $orderInfo = $resultOrder->row();
        if ($orderInfo->status == 2) {
            $this->redirect('tourism/tourism/paySuccess');
        }
        if ($orderInfo->status != 1) {
            $this->alertJumpPre('订单状态有误');
        }
        return $orderInfo;
    }
}
